package com.zx.练习题.demo;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class T2 {

    public static void main(String[] args) throws Exception {
        int parties = 2;//等待的线程数

        ExecutorService pool = Executors.newCachedThreadPool();

        final CyclicBarrier cyclicBarrier = new CyclicBarrier(parties, () -> {
            pool.execute(() -> {
                log.info("开始执行任务 1");
            });
            pool.execute(() -> {
                log.info("开始执行任务 2");
            });
        });

        pool.execute(() -> {
            try {
                log.info("start 1");
                Thread.sleep(1000L);
                log.info("end 1");
                cyclicBarrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        pool.execute(() -> {
            try {
                log.info("start 2");
                Thread.sleep(1000L);
                log.info("end 2");
                cyclicBarrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        pool.shutdown();
    }

    // 控制同时运行的线程数
    public static void main2(String[] args) {
        int ThreadToatl = 10;//线程数
        int permits = 2;//等待的线程数
        Semaphore semaphore = new Semaphore(permits);
        ExecutorService pool = Executors.newCachedThreadPool();

        for (int i = 0; i < ThreadToatl; i++) {
            final int idx = i;
            pool.execute(() -> {
                try {
                    semaphore.acquire();
                    Thread.sleep(1000L);
                    System.out.println(idx);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            });
        }


    }
}
